<?php

/**
 * @author Thibaut Cromphaut, Gaïtano Boeraeve, Mathias Helin, Dimitry Dierickx
 * @copyright  Copyright (c) 2011 Artevelde University College Ghent 
 */


class Ahs_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{

    protected $_acl;

    public function __construct()
    {
        $session = new Zend_Session_Namespace('acl');
        if ( isset($session->acl) ) {
            $session->acl = $this->_acl = new Ahs_Acl();
            //$this->_acl = $session->acl;
        } else {
            $session->acl = $this->_acl = new Ahs_Acl();
        }
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        parent::preDispatch($request);

        $request = $this->getRequest();

        $auth    = Zend_Auth::getInstance();
        $storage = $auth->getStorage()->read();
        $role    = $auth->hasIdentity() ? $storage->Role->Name : 'Guest';
        
        $module     = $request->getModuleName()     . 'Module';
        $controller = $request->getControllerName() . 'Controller';
        $action     = $request->getActionName()     . 'Action';

        $acl = $this->_acl;
        $resource  = $module;
        $privilege = $controller;
        if ( $acl->isAllowed($role, $resource, $privilege) ) {
            $resource  = ($module == 'defaultModule' ? $controller : "{$module}.{$controller}");
            $privilege = $action;

            if ( $acl->isAllowed($role, $resource, $privilege) ) {
                return true;
            }
        }

        throw new Exception("Access violation for role '{$role}'");
    }
}

?>
